﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Web;
using wojilu.Web.Context;
using wojilu.Web.Mvc;

namespace wojilu.Web.Code
{
    /// <summary>
    /// 验证码输出类
    /// </summary>
    public class VerifyCode
    {
        public static string ChineseChars = string.Empty;
        /// <summary>
        /// 输出验证图片
        /// </summary>
        /// <param name="Index">选择的样式</param>
        public void DrawImage(int Index)
        {
            string thecode = CreateVerifyCode();
            HttpContext.Current.Session[Captcha.sessionName] = thecode.ToLower();
            CreateImage(thecode, Index);
        }

        /// <summary>
        /// 输出验证图片
        /// </summary>
        /// <param name="Index">选择的样式</param>
        /// <param name="codeLen">字符串长度</param>
        /// <param name="zhCharsCount">中文字符数</param>
        public void DrawImage(int Index, int codeLen, int zhCharsCount)
        {
            string thecode = CreateVerifyCode(codeLen, zhCharsCount);
            HttpContext.Current.Session[Captcha.sessionName] = thecode.ToLower();
            CreateImage(thecode, Index);
        }

        /// <summary>
        /// 输出验证图片
        /// </summary>
        /// <param name="Index">选择的样式</param>
        /// <param name="thecode">字符串</param>
        public void DrawImage(string thecode, int Index)
        {
            HttpContext.Current.Session[Captcha.sessionName] = thecode.ToLower();
            CreateImage(thecode, Index);
        }

        public VerifyCode()
        {
            rnd = new Random(unchecked((int)DateTime.Now.Ticks));
        }

        /// <summary>
        /// 全局随机数生成器
        /// </summary>
        private Random rnd;

        #region 英文与数字串
        string englishornumchars = "0123456789abcdefghjkmnpqrstuvwxy";
        /// <summary>
        /// 验证码范围
        /// </summary>
        public string EnglishOrNumChars
        {
            get { return englishornumchars; }
            set { englishornumchars = value; }
        }
        #endregion

        #region 验证码长度(默认6个验证码的长度
        private int length = 6;
        public int Length
        {
            get { return length; }
            set { length = value; }
        }
        #endregion

        int fontSize = 18;
        /// <summary>
        /// 验证码字体大小(为了显示扭曲效果，默认30像素，可以自行修改)
        /// </summary>
        public int FontSize
        {
            get { return fontSize; }
            set { fontSize = value; }
        }

        bool fontStyleBol = true;
        /// <summary>
        /// 是否设置字体Style，默认为True
        /// </summary>
        public bool FontStyleBol
        {
            get { return fontStyleBol; }
            set { fontStyleBol = value; }
        }

        FontStyle fontStyles = FontStyle.Bold;
        /// <summary>
        /// 字体Style设置,默认为Bold
        /// </summary>
        public FontStyle FontStyles
        {
            get { return fontStyles; }
            set { fontStyles = value; }
        }

        int padding = 4;
        /// <summary>
        /// 边框补(默认4像素)
        /// </summary>
        public int Padding
        {
            get { return padding; }
            set { padding = value; }
        }

        bool chaos = true;
        /// <summary>
        /// 是否输出燥点(默认输出)
        /// </summary>
        public bool Chaos
        {
            get { return chaos; }
            set { chaos = value; }
        }

        Color chaosColor = Color.LightGray;
        /// <summary>
        /// 输出燥点的颜色(默认灰色)
        /// </summary>
        public Color ChaosColor
        {
            get { return chaosColor; }
            set { chaosColor = value; }
        }

        Color backgroundColor = Color.White;
        /// <summary>
        /// 自定义背景色(默认白色)
        /// </summary>
        public Color BackgroundColor
        {
            get { return backgroundColor; }
            set { backgroundColor = value; }
        }

        Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
        /// <summary>
        /// 自定义随机颜色数组
        /// </summary>
        public Color[] Colors
        {
            get { return colors; }
            set { colors = value; }
        }

        string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "黑体", "Arial", "宋体" };
        /// <summary>
        /// 自定义字体数组
        /// </summary>
        public string[] Fonts
        {
            get { return fonts; }
            set { fonts = value; }
        }

        private string codeSerial = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
        /// <summary>
        /// 自定义随机码字符串序列(使用逗号分隔)
        /// </summary>
        public string CodeSerial
        {
            get { return codeSerial; }
            set { codeSerial = value; }
        }

        private bool fontLQ = false;
        /// <summary>
        ///  是否字体抽曲,默认为False
        /// </summary>
        public bool FontLQ
        {
            get { return fontLQ; }
            set { fontLQ = value; }
        }

        private int multValue = 3;

        /// <summary>
        /// 波形的幅度倍数，越大扭曲的程度越高，一般为3
        /// </summary>
        public int MultValue
        {
            get { return multValue; }
            set { multValue = value; }
        }

        private bool creatImgnum = false;
        /// <summary>
        /// 默认不生成图片，以浏览器缓冲显示
        /// </summary>
        public bool CreatImgNum
        {
            get { return creatImgnum; }
            set { creatImgnum = value; }
        }


        private string creatImgPath = "";
        /// <summary>
        /// 当选择生成图片时，此路径必填，不然返回错误
        /// </summary>
        public string CreatImgPath
        {
            get { return creatImgPath; }
            set { creatImgPath = value; }
        }

        #region 产生波形滤镜效果

        private const double PI = 3.1415926535897932384626433832795;
        private const double PI2 = 6.283185307179586476925286766559;

        /// <summary>
        /// 正弦曲线Wave扭曲图片
        /// </summary>
        /// <param name="srcBmp">图片路径</param>
        /// <param name="bXDir">如果扭曲则选择为True</param>
        /// <param name="nMultValue">波形的幅度倍数，越大扭曲的程度越高，一般为3</param>
        /// <param name="dPhase">波形的起始相位，取值区间[0-2*PI)</param>
        /// <returns></returns>
        public Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
        {
            Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);

            // 将位图背景填充为白色
            System.Drawing.Graphics graph = Graphics.FromImage(destBmp);
            graph.FillRectangle(new SolidBrush(Color.White), 0, 0, destBmp.Width, destBmp.Height);
            graph.Dispose();

            double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;

            for (int i = 0; i < destBmp.Width; i++)
            {
                for (int j = 0; j < destBmp.Height; j++)
                {
                    double dx = 0;
                    dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;
                    dx += dPhase;
                    double dy = Math.Sin(dx);

                    // 取得当前点的颜色
                    int nOldX = 0, nOldY = 0;
                    nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
                    nOldY = bXDir ? j : j + (int)(dy * dMultValue);

                    System.Drawing.Color color = srcBmp.GetPixel(i, j);
                    if (nOldX >= 0 && nOldX < destBmp.Width
                     && nOldY >= 0 && nOldY < destBmp.Height)
                    {
                        destBmp.SetPixel(nOldX, nOldY, color);
                    }
                }
            }

            return destBmp;
        }

        #endregion

        /// <summary>
        /// 生成校验码图片
        /// </summary>
        /// <param name="code">验证码</param>
        /// <returns></returns>
        public Bitmap CreateImage(string code)
        {
            int fSize = FontSize;
            int fWidth = fSize + Padding;

            int imageWidth = (int)(code.Length * fWidth) + 4 + Padding * 2;
            int imageHeight = int.Parse((fSize * 1.5 + Padding * 1.5).ToString());

            Bitmap image = new Bitmap(imageWidth, imageHeight);

            Graphics g = Graphics.FromImage(image);

            g.Clear(BackgroundColor);

            //给背景添加随机生成的燥点
            if (this.Chaos)
            {

                Pen pen = new Pen(ChaosColor, 0);
                int c = Length * 10;

                for (int i = 0; i < c; i++)
                {
                    int x = rnd.Next(image.Width);
                    int y = rnd.Next(image.Height);

                    g.DrawRectangle(pen, x, y, 1, 1);
                }
            }

            int left = 0, top = 0, top1 = 1, top2 = 1;

            int n1 = (imageHeight - FontSize - Padding * 2);
            int n2 = n1 / 4;
            top1 = n2;
            top2 = n2 * 2;

            Font f;
            Brush b;

            int cindex, findex;

            //随机字体和颜色的验证码字符
            for (int i = 0; i < code.Length; i++)
            {
                cindex = rnd.Next(Colors.Length - 1);
                findex = rnd.Next(Fonts.Length - 1);

                if (FontStyleBol == true) f = new System.Drawing.Font(Fonts[findex], fSize, FontStyles);
                else { f = new Font(Fonts[findex], fSize); }


                b = new System.Drawing.SolidBrush(Colors[cindex]);

                if (i % 2 == 1)
                {
                    top = top2;
                }
                else
                {
                    top = top1;
                }

                left = i * fWidth;

                g.DrawString(code.Substring(i, 1), f, b, left, top);
            }

            //画一个边框 边框颜色为Color.Gainsboro
            g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
            g.Dispose();

            //产生波形
            image = TwistImage(image, FontLQ, 0, 4);

            return image;
        }

        /// <summary>
        /// 生成校验码图片
        /// </summary>
        /// <param name="checkcode">验证码</param>
        /// <param name="index">样式选择</param>
        public void CreateImage(string checkcode, int index)
        {
            if (checkcode == null || checkcode.Trim() == String.Empty)
                return;
            if (index == 0)
            {
                int fSize = FontSize;
                int fWidth = fSize + Padding;
                int imageWidth = (int)(checkcode.Length * fWidth) + 4 + Padding * 2;
                int imageHeight = int.Parse((fSize * 1.5 + Padding * 1.5).ToString());

                System.Drawing.Bitmap image = new Bitmap(imageWidth, imageHeight);
                Graphics g = Graphics.FromImage(image);

                try
                {
                    //生成随机生成器
                    Random random = new Random();

                    //清空图片背景色
                    g.Clear(Color.White);

                    //画图片的背景噪音线
                    for (int i = 0; i < 25; i++)
                    {
                        int x1 = random.Next(image.Width);
                        int x2 = random.Next(image.Width);
                        int y1 = random.Next(image.Height);
                        int y2 = random.Next(image.Height);

                        g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                    }

                    int left = 0, top = 0, top1 = 1, top2 = 1;

                    int n1 = (imageHeight - FontSize - Padding * 2);
                    int n2 = n1 / 4;
                    top1 = n2;
                    top2 = n2 * 2;
                    int cindex, findex;
                    Font f;
                    Brush b;
                    //随机字体和颜色的验证码字符
                    for (int i = 0; i < checkcode.Length; i++)
                    {
                        cindex = rnd.Next(Colors.Length - 1);
                        findex = rnd.Next(Fonts.Length - 1);

                        if (FontStyleBol == true) f = new System.Drawing.Font(Fonts[findex], fSize, FontStyles);
                        else { f = new Font(Fonts[findex], fSize); }


                        b = new System.Drawing.SolidBrush(Colors[cindex]);

                        if (i % 2 == 1)
                        {
                            top = top2;
                        }
                        else
                        {
                            top = top1;
                        }

                        left = i * fWidth;

                        g.DrawString(checkcode.Substring(i, 1), f, b, left, top);
                    }

                    //画图片的前景噪音点s
                    for (int i = 0; i < 100; i++)
                    {
                        int x = random.Next(image.Width);
                        int y = random.Next(image.Height);

                        image.SetPixel(x, y, Color.FromArgb(random.Next()));
                    }

                    //画图片的边框线
                    g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                    g.Dispose();
                    //产生波形
                    image = TwistImage(image, FontLQ, 0, 4);

                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    HttpContext.Current.Response.ClearContent();
                    HttpContext.Current.Response.ContentType = "image/Png";
                    HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                }
                finally
                {
                    g.Dispose();
                    image.Dispose();
                }
                return;
            }
            if (index == 1)
            {
                int width = checkcode.Length * 13;
                Bitmap image = new Bitmap(width, 0x19);
                Graphics graphics = Graphics.FromImage(image);
                graphics.Clear(Color.White);
                Color[] colorArray = new Color[] { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
                string[] strArray = new string[] { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "黑体", "Arial", "宋体" };
                Random random = new Random();
                for (int i = 0; i < 50; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    graphics.DrawRectangle(new Pen(Color.LightGray, 0f), x, y, 1, 1);
                }
                for (int j = 0; j < checkcode.Length; j++)
                {
                    int index1 = random.Next(7);
                    int num7 = random.Next(5);
                    Font font = new Font(strArray[num7], 10f, FontStyle.Bold);
                    Brush brush = new SolidBrush(colorArray[index1]);
                    int num8 = 4;
                    if (((j + 1) % 2) == 0)
                    {
                        num8 = 2;
                    }
                    graphics.DrawString(checkcode.Substring(j, 1), font, brush, (float)(3 + (j * 12)), (float)num8);
                }
                graphics.DrawRectangle(new Pen(Color.Black, 0f), 0, 0, image.Width - 1, image.Height - 1);
                MemoryStream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Png);
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ContentType = "image/Png";
                HttpContext.Current.Response.BinaryWrite(stream.ToArray());
                graphics.Dispose();
                image.Dispose();

                return;
            }
            if (index == 2)
            {
                int letterWidth = 20;//单个字体的宽度范围
                int letterHeight = 20;//单个字体的高度范围
                Font theFont = new Font("Arial", 11, FontStyle.Bold);//字体
                int int_ImageWidth = checkcode.Length * letterWidth;
                Random newRandom = new Random();
                Bitmap image = new Bitmap(int_ImageWidth, letterHeight);
                Graphics g = Graphics.FromImage(image);
                //生成随机生成器
                Random random = new Random();
                //白色背景
                g.Clear(Color.White);
                //画图片的背景噪音线
                for (int i = 0; i < 10; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);

                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }

                //画图片的前景噪音点
                for (int i = 0; i < 10; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);

                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //灰色边框
                g.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, (letterHeight - 1));

                for (int int_index = 0; int_index < checkcode.Length; int_index++)
                {
                    string str_char = checkcode.Substring(int_index, 1);
                    Brush newBrush = new SolidBrush(GetRandomColor());
                    Point thePos = new Point(int_index * letterWidth + 1 + newRandom.Next(3), 1 + newRandom.Next(3));
                    g.DrawString(str_char, theFont, newBrush, thePos);
                }

                //将生成的图片发回客户端
                MemoryStream ms = new MemoryStream();
                image.Save(ms, ImageFormat.Png);
                HttpContext.Current.Response.ClearContent(); //需要输出图象信息 要修改HTTP头 
                HttpContext.Current.Response.ContentType = "image/Png";
                HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                g.Dispose();
                image.Dispose();
                HttpContext.Current.Response.End();
                return;
            }
            if (index == 3)
            {
                Bitmap image = CreateImage(checkcode);
                if (CreatImgNum == false)
                {
                    MemoryStream ms = new MemoryStream();
                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    HttpContext.Current.Response.ClearContent();
                    HttpContext.Current.Response.ContentType = "image/Png";
                    HttpContext.Current.Response.BinaryWrite(ms.GetBuffer());
                }
                else
                {
                    try
                    {
                        image.Save(CreatImgPath, System.Drawing.Imaging.ImageFormat.Png);
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                }
                image.Dispose();
                return;
            }
            if (index == 4)
            {
                Bitmap image = new Bitmap((int)Math.Ceiling((double)(checkcode.Length * 12.5)), 0x16);
                Graphics graphics = Graphics.FromImage(image);
                try
                {
                    Random random = new Random();
                    graphics.Clear(Color.White);
                    for (int i = 0; i < 0x19; i++)
                    {
                        int num2 = random.Next(image.Width);
                        int num3 = random.Next(image.Width);
                        int num4 = random.Next(image.Height);
                        int num5 = random.Next(image.Height);
                        graphics.DrawLine(new Pen(Color.Silver), num2, num4, num3, num5);
                    }
                    Font font = new Font("Arial", 12f, FontStyle.Italic | FontStyle.Bold);
                    LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                    graphics.DrawString(checkcode, font, brush, (float)2f, (float)2f);
                    for (int j = 0; j < 100; j++)
                    {
                        int x = random.Next(image.Width);
                        int y = random.Next(image.Height);
                        image.SetPixel(x, y, Color.FromArgb(random.Next()));
                    }
                    graphics.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                    MemoryStream stream = new MemoryStream();
                    image.Save(stream, ImageFormat.Gif);
                    HttpContext.Current.Response.ClearContent();
                    HttpContext.Current.Response.ContentType = "image/Gif";
                    HttpContext.Current.Response.BinaryWrite(stream.ToArray());
                }
                finally
                {
                    graphics.Dispose();
                    image.Dispose();
                }
                return;
            }
        }

        /// <summary>
        /// 生成随机字符码
        /// </summary>
        /// <param name="codeLen">字符串长度</param>
        /// <param name="zhCharsCount">中文字符数</param>
        /// <returns></returns>
        public string CreateVerifyCode(int codeLen, int zhCharsCount)
        {
            char[] chs = new char[codeLen];

            int index;
            for (int i = 0; i < zhCharsCount; i++)
            {
                index = rnd.Next(0, codeLen);
                if (chs[index] == '\0')
                    chs[index] = CreateZhChar();
                else
                    --i;
            }
            for (int i = 0; i < codeLen; i++)
            {
                if (chs[i] == '\0')
                    chs[i] = CreateEnOrNumChar();
            }

            return new string(chs, 0, chs.Length);
        }

        /// <summary>
        /// 生成默认长度5的随机字符码
        /// </summary>
        /// <returns></returns>
        public string CreateVerifyCode()
        {
            return CreateVerifyCode(Length, 0);
        }

        /// <summary>
        /// 生成英文或数字字符
        /// </summary>
        /// <returns></returns>
        protected char CreateEnOrNumChar()
        {
            return EnglishOrNumChars[rnd.Next(0, EnglishOrNumChars.Length)];
        }

        /// <summary>
        /// 生成汉字字符
        /// </summary>
        /// <returns></returns>
        public char CreateZhChar()
        {
            //若提供了汉字集，查询汉字集选取汉字
            if (ChineseChars.Length > 0)
            {
                return ChineseChars[rnd.Next(0, ChineseChars.Length)];
            }
            //若没有提供汉字集，则根据《GB2312简体中文编码表》编码规则构造汉字
            else
            {
                byte[] bytes = new byte[2];

                //第一个字节值在0xb0, 0xf7之间
                bytes[0] = (byte)rnd.Next(0xb0, 0xf8);
                //第二个字节值在0xa1, 0xfe之间
                bytes[1] = (byte)rnd.Next(0xa1, 0xff);

                //根据汉字编码的字节数组解码出中文汉字
                string str1 = Encoding.GetEncoding("gb2312").GetString(bytes);

                return str1[0];
            }
        }

        public Color GetRandomColor()
        {
            Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
            System.Threading.Thread.Sleep(RandomNum_First.Next(50));
            Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);

            //  为了在白色背景上显示，尽量生成深色
            //int int_Red = RandomNum_First.Next(256);
            //int int_Green = RandomNum_Sencond.Next(256);
            //int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
            //int_Blue = (int_Blue > 255) ? 255 : int_Blue;
            int int_Red = RandomNum_First.Next(180);
            int int_Green = RandomNum_Sencond.Next(180);
            int int_Blue = (int_Red + int_Green > 300) ? 0 : 400 - int_Red - int_Green;
            int_Blue = (int_Blue > 255) ? 255 : int_Blue;
            return Color.FromArgb(int_Red, int_Green, int_Blue);
        }

        /// <summary>
        /// 验证码生成的取值范围
        /// </summary>
        private static string[] verifycodeRange = { "1","2","3","4","5","6","7","8","9",
                                                    "a","b","c","d","e","f","g",
                                                    "h",    "j","k",    "m","n",
                                                        "p","q",    "r","s","t",
                                                    "u","v","w",    "x","y"
                                                  };

        /// <summary>
        /// 生成验证码所使用的随机数发生器
        /// </summary>
        private static Random verifycodeRandom = new Random(unchecked((int)DateTime.Now.Ticks));

        /// <summary>
        /// 产生验证码
        /// </summary>
        /// <param name="len">长度</param>
        /// <returns>验证码</returns>
        public static string CreateAuthStr(int len)
        {
            int number;
            StringBuilder checkCode = new StringBuilder();
            Random random = new Random();

            for (int i = 0; i < len; i++)
            {
                number = random.Next();

                if (number % 2 == 0)
                    checkCode.Append((char)('0' + (char)(number % 10)));
                else
                    checkCode.Append((char)('A' + (char)(number % 26)));
            }
            return checkCode.ToString();
        }

        /// <summary>
        /// 产生验证码
        /// </summary>
        /// <param name="len">长度</param>
        /// <param name="OnlyNum">是否仅为数字</param>
        /// <returns>string</returns>
        public static string CreateAuthStr(int len, bool OnlyNum)
        {
            int number;
            StringBuilder checkCode = new StringBuilder();

            for (int i = 0; i < len; i++)
            {
                if (!OnlyNum)
                    number = verifycodeRandom.Next(0, verifycodeRange.Length);
                else
                    number = verifycodeRandom.Next(0, 10);

                checkCode.Append(verifycodeRange[number]);
            }
            return checkCode.ToString();
        }

        //------------------------------------------------------------------------------------

        /// <summary>
        /// 检查用户提交的验证码是否错误
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public Boolean CheckError(MvcContext ctx)
        {
            String validationText = ClientCode(ctx);
            if (isCodeError(validationText, ctx))
            {
                ctx.errors.Add(lang.get("exValidateCodeError"));
                return true;
            }
            return false;
        }

        private Boolean isCodeError(String userCode, MvcContext ctx)
        {
            if (strUtil.IsNullOrEmpty(userCode)) return true;

            String serverCode = CorrectCode(ctx);
            return !strUtil.EqualsIgnoreCase(userCode, serverCode);
        }

        /// <summary>
        /// 服务器端正确的验证码
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public String CorrectCode(MvcContext ctx)
        {
            return ctx.web.SessionGet(Captcha.sessionName) as string;
        }

        /// <summary>
        /// 用户实际提交的验证码
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public String ClientCode(MvcContext ctx)
        {
            return ctx.Post(inputName);
        }

        public static readonly String inputName = "seccode";
    }
}